package com.bawei.bydayzg_two

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.base.mvvm.BaseActivity
import com.bawei.base.room.KeyEntity
import com.bawei.base.room.UserUtils
import com.bawei.bydayzg_two.adapter.GoodsAdapter
import com.bawei.bydayzg_two.adapter.KeyAdapter
import com.bawei.bydayzg_two.databinding.ActivitySearchBinding
import com.bawei.bydayzg_two.viewModel.SearchViewModel
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.chip.Chip
import java.util.Timer
import java.util.TimerTask
import kotlin.concurrent.timerTask

@Route(path = "/app/SearchActivity")
class SearchActivity : BaseActivity<ActivitySearchBinding,SearchViewModel>() {
    lateinit var goodsAdapter: GoodsAdapter
    //
    var cid:Int = 0
    var keyword:String = ""
    var limit:Int = 0
    var news:Boolean = false
    var page:Int = 0
    var priceOrder:String = ""
    var salesOrder:String = ""
    //
    lateinit var time:Timer
    var index = 0
    val handler = Handler()
    //
    override fun getLoutyId(): Int {
        return R.layout.activity_search
    }

    override fun getViewModel(): Class<SearchViewModel> {
        return SearchViewModel::class.java
    }

    override fun initView() {

        //模拟关键词每2秒切换
        val keys = mutableListOf("女士","茶","张徐")
        time = Timer()
        //b n
        time.schedule(timerTask {
            handler.post {
                binding.sv.queryHint = keys[index]
                index ++
                //当index大于最大下标时，index重新赋值
                if (index > keys.size - 1){
                    index = 0
                }
            }
        },0,2000)

        goodsAdapter = GoodsAdapter()
        binding.rvGoods.adapter = goodsAdapter
        binding.rvGoods.layoutManager = GridLayoutManager(this,2)

        //选择价格排序那么销量就没有顺序    悬着销量排序那么价格就没有顺序
        binding.tvPrice.setOnClickListener {
            if (priceOrder == ""){
                //第一次点击
                priceOrder = "asc"
                binding.ivPrcie.setImageResource(R.mipmap.by3)
            } else if (priceOrder == "asc"){
                priceOrder = "desc"
                //
                binding.ivPrcie.setImageResource(R.mipmap.by1)
            } else {
                priceOrder = ""
                binding.ivPrcie.setImageResource(R.mipmap.by2)
            }

            //销量无意义
            salesOrder = ""
            binding.ivSale.setImageResource(R.mipmap.by2)
            viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
        }

        //价格排序
        binding.tvSale.setOnClickListener {
            if (salesOrder == ""){
                //第一次点击
                salesOrder = "asc"
                binding.ivSale.setImageResource(R.mipmap.by3)
            } else if (salesOrder == "asc"){
                salesOrder = "desc"
                //
                binding.ivSale.setImageResource(R.mipmap.by1)
            } else {
                salesOrder = ""
                binding.ivSale.setImageResource(R.mipmap.by2)
            }

            //销量无意义
            priceOrder = ""
            binding.ivPrcie.setImageResource(R.mipmap.by2)
            viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
        }

        //点击新品文字变成红色，再次点击变成黑色
        binding.tvNew.setOnClickListener {
            //如果为true则代表是新品
            if (news){
                binding.tvNew.setTextColor(Color.BLACK)
                //
                news = false
            } else {
                binding.tvNew.setTextColor(Color.RED)
                //
                news = true
            }
            //
            viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
        }

        //yugyugygygyugyugyugyg
        queryKey()
        //查询
        binding.sv.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {//回车查询
                //点击回车按钮时执行下方方法
                if (query != null){
                    keyword = query
                    //
                    viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
                    //
                    UserUtils.getDB().getKey().insert(KeyEntity(query))
                    //
                    queryKey()
                }
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                //文字发生变化时执行的方法  注释掉就不会再实时查询了
                if (newText != null){
                    keyword = newText
                    //
                    viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
                    //
                    ToastUtils.showLong(newText)
                }
                return false
            }
        })



        //清空所有
        binding.tvClear.setOnClickListener {
            UserUtils.getDB().getKey().deleteAll()
            //删除页面所有
            binding.cg.removeAllViews()
        }
    }

    private fun queryKey() {
        val list = UserUtils.getDB().getKey().query()
        list.reverse()
        //将之前展示的历史记录清空
        binding.cg.removeAllViews()
        if (list.size > 0){
            list.forEach {
                //循环创建chip
                val chip = LayoutInflater.from(this).inflate(R.layout.item_cg, null) as Chip
                //给对应的chip的文本设置对应的内容
                chip.findViewById<TextView>(R.id.cg_name).text = it.keyword
                binding.cg.addView(chip)

                //点击chip可以进行再次搜索
                chip.setOnClickListener {it1->
                    binding.sv.setQuery(it.keyword,true)
                }
                //删除chip
                chip.setOnCloseIconClickListener {it2->
                    //先删除数据库的数据
                    UserUtils.getDB().getKey().delete(it)
                    //再删除页面数据
                    binding.cg.removeView(it2)
                }
            }
        }
    }

    override fun initDate() {

        //
        viewModel.goodsSuccess.observe(this){
            if (it.code == 200){
                goodsAdapter.data.clear()
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
            }
            //
            ToastUtils.showLong(it.message)
        }

    }

}